package com.hospital.workstation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ObjectUtil;
import com.hospital.common.core.domain.R;
import com.hospital.common.utils.StringUtils;
import com.hospital.common.core.page.TableDataInfo;
import com.hospital.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hospital.workstation.constant.DictConstants;
import com.hospital.workstation.domain.PatientBaseInfo;
import com.hospital.workstation.domain.TwoLevel;
import com.hospital.workstation.domain.vo.CareLevelTriggerItemVo;
import com.hospital.workstation.domain.vo.PatientBaseInfoVo;
import com.hospital.workstation.domain.vo.TwoLevelVo;
import com.hospital.workstation.mapper.PatientBaseInfoMapper;
import com.hospital.workstation.mapper.TwoLevelMapper;
import com.hospital.workstation.utils.CareLevelUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.hospital.workstation.domain.bo.FirstLevelBo;
import com.hospital.workstation.domain.vo.FirstLevelVo;
import com.hospital.workstation.domain.FirstLevel;
import com.hospital.workstation.mapper.FirstLevelMapper;
import com.hospital.workstation.service.IFirstLevelService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 医学一级监护信息Service业务层处理
 *
 * @author whb
 * @date 2023-04-18
 */
@RequiredArgsConstructor
@Service
public class FirstLevelServiceImpl implements IFirstLevelService {

    private final FirstLevelMapper baseMapper;
    private final PatientBaseInfoMapper patientBaseInfoMapper;
    private final TwoLevelMapper twoLevelMapper;

    /**
     * 查询医学一级监护信息
     */
    @Override
    public FirstLevelVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询医学一级监护信息列表
     */
    @Override
    public TableDataInfo<FirstLevelVo> queryPageList(FirstLevelBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<FirstLevel> lqw = buildQueryWrapper(bo);
        Page<FirstLevelVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询医学一级监护信息列表
     */
    @Override
    public List<FirstLevelVo> queryList(FirstLevelBo bo) {
        LambdaQueryWrapper<FirstLevel> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<FirstLevel> buildQueryWrapper(FirstLevelBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<FirstLevel> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getMedicalRecordNo() != null, FirstLevel::getMedicalRecordNo, bo.getMedicalRecordNo());
        lqw.eq(StringUtils.isNotBlank(bo.getRenalFunction()), FirstLevel::getRenalFunction, bo.getRenalFunction());
        lqw.eq(StringUtils.isNotBlank(bo.getBloodDialysis()), FirstLevel::getBloodDialysis, bo.getBloodDialysis());
        lqw.eq(StringUtils.isNotBlank(bo.getHemofiltration()), FirstLevel::getHemofiltration, bo.getHemofiltration());
        lqw.eq(StringUtils.isNotBlank(bo.getBloodReplacement()), FirstLevel::getBloodReplacement, bo.getBloodReplacement());
        lqw.eq(StringUtils.isNotBlank(bo.getBloodPerfusion()), FirstLevel::getBloodPerfusion, bo.getBloodPerfusion());
        lqw.eq(StringUtils.isNotBlank(bo.getExtracorporeal()), FirstLevel::getExtracorporeal, bo.getExtracorporeal());
        lqw.eq(StringUtils.isNotBlank(bo.getAltValue()), FirstLevel::getAltValue, bo.getAltValue());
        lqw.eq(StringUtils.isNotBlank(bo.getAstValue()), FirstLevel::getAstValue, bo.getAstValue());
        lqw.eq(StringUtils.isNotBlank(bo.getAlpValue()), FirstLevel::getAlpValue, bo.getAlpValue());
        lqw.eq(StringUtils.isNotBlank(bo.getTbil()), FirstLevel::getTbil, bo.getTbil());
        lqw.eq(StringUtils.isNotBlank(bo.getCtpValue()), FirstLevel::getCtpValue, bo.getCtpValue());
        lqw.eq(StringUtils.isNotBlank(bo.getShowShock()), FirstLevel::getShowShock, bo.getShowShock());
        lqw.eq(StringUtils.isNotBlank(bo.getArteryBloodCheck()), FirstLevel::getArteryBloodCheck, bo.getArteryBloodCheck());
        lqw.eq(StringUtils.isNotBlank(bo.getNtProBnp()), FirstLevel::getNtProBnp, bo.getNtProBnp());
        lqw.eq(StringUtils.isNotBlank(bo.getCtNt()), FirstLevel::getCtNt, bo.getCtNt());
        lqw.eq(StringUtils.isNotBlank(bo.getBloodClotting()), FirstLevel::getBloodClotting, bo.getBloodClotting());
        lqw.eq(StringUtils.isNotBlank(bo.getPillsCount()), FirstLevel::getPillsCount, bo.getPillsCount());
        lqw.eq(StringUtils.isNotBlank(bo.getUnionAntineoplastic()), FirstLevel::getUnionAntineoplastic, bo.getUnionAntineoplastic());
        lqw.eq(StringUtils.isNotBlank(bo.getThrombolyticTherapy()), FirstLevel::getThrombolyticTherapy, bo.getThrombolyticTherapy());
        lqw.eq(StringUtils.isNotBlank(bo.getAdrAde()), FirstLevel::getAdrAde, bo.getAdrAde());
        lqw.eq(StringUtils.isNotBlank(bo.getSpecialAntibiosis()), FirstLevel::getSpecialAntibiosis, bo.getSpecialAntibiosis());
        lqw.eq(StringUtils.isNotBlank(bo.getExtremelyPoisonousDrugs()), FirstLevel::getExtremelyPoisonousDrugs, bo.getExtremelyPoisonousDrugs());
        lqw.eq(StringUtils.isNotBlank(bo.getHighWarningPills()), FirstLevel::getHighWarningPills, bo.getHighWarningPills());
        lqw.eq(StringUtils.isNotBlank(bo.getCareLevelValue()), FirstLevel::getCareLevelValue, bo.getCareLevelValue());
        lqw.eq(StringUtils.isNotBlank(bo.getTwoChronicDisease()), FirstLevel::getTwoChronicDisease, bo.getTwoChronicDisease());
        return lqw;
    }

    /**
     * 新增医学一级监护信息
     */
    @Override
    public Boolean insertByBo(FirstLevelBo bo) {
        FirstLevel add = BeanUtil.toBean(bo, FirstLevel.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改医学一级监护信息
     */
    @Override
    public Boolean updateByBo(FirstLevelBo bo) {
        FirstLevel update = BeanUtil.toBean(bo, FirstLevel.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(FirstLevel entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除医学一级监护信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 查询医学一级监护信息详细信息
     *
     * @param medicalRecordNo 病历号
     * @return
     */
    @Override
    public FirstLevelVo queryByMedicalRecordNo(Integer medicalRecordNo) {
        return baseMapper.selectVoOne(new LambdaQueryWrapper<FirstLevel>().eq(FirstLevel::getMedicalRecordNo, medicalRecordNo));
    }

    /**
     * 新增或修改一级监护信息
     *
     * @param bo 一级监护信息对象
     * @return
     */
    @Transactional
    @Override
    public Boolean insertOrUpdateByBo(FirstLevelBo bo) {
        try {
            // 更新一级监护信息
            FirstLevel firstLevel = BeanUtil.toBean(bo, FirstLevel.class);
            baseMapper.updateById(firstLevel);
            // 查询患者的基本信息
            PatientBaseInfo baseInfo = patientBaseInfoMapper.selectOne(new LambdaQueryWrapper<PatientBaseInfo>().eq(PatientBaseInfo::getMedicalRecordNo, firstLevel.getMedicalRecordNo()));
            // 判断患者是否属于一级监护信息
            if (ObjectUtil.isNotNull(firstLevel) && ObjectUtil.isNotNull(baseInfo)) {
                boolean isFirst = CareLevelUtil.isFirstCareLevel(baseInfo, firstLevel);
                if (isFirst) { // 属于一级监护，更新患者监护分级
                    baseInfo.setGuardianLevel(DictConstants.GUARDIAN_LEVEL_THREE);
                    patientBaseInfoMapper.updateById(baseInfo);
                } else { // 不属于一级监护
                    // 查询药学二级监护信息
                    TwoLevel twoLevel = twoLevelMapper.selectOne(new LambdaQueryWrapper<TwoLevel>().eq(TwoLevel::getMedicalRecordNo, firstLevel.getMedicalRecordNo()));
                    // 判断是否属于二级监护
                    boolean isTwo = CareLevelUtil.isTwoCareLevel(baseInfo, twoLevel);
                    if (isTwo) { // 设置为二级
                        baseInfo.setGuardianLevel(DictConstants.GUARDIAN_LEVEL_TWO);
                    } else { // 设置为三级
                        baseInfo.setGuardianLevel(DictConstants.GUARDIAN_LEVEL_ONE);
                    }
                    // 更新患者药学监护分级
                    patientBaseInfoMapper.updateById(baseInfo);
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取医学监护标红项信息
     *
     * @param medicalRecordNo 病历号
     * @return
     */
    @Override
    public R<CareLevelTriggerItemVo> getRedItemVo(Integer medicalRecordNo) {
        try {
            // 创建药学监护信息触发项视图对象
            CareLevelTriggerItemVo careLevelTriggerItemVo = new CareLevelTriggerItemVo();
            // 查询患者基本信息实体对象
            PatientBaseInfo patientBaseInfo = patientBaseInfoMapper.selectOne(new LambdaQueryWrapper<PatientBaseInfo>().eq(PatientBaseInfo::getMedicalRecordNo, medicalRecordNo));
            // 查询一级监护信息视图对象
            FirstLevelVo firstLevelVo = baseMapper.selectVoOne(new LambdaQueryWrapper<FirstLevel>().eq(FirstLevel::getMedicalRecordNo, medicalRecordNo));
            // 查询二级监护信息视图对象
            TwoLevelVo twoLevelVo = twoLevelMapper.selectVoOne(new LambdaQueryWrapper<TwoLevel>().eq(TwoLevel::getMedicalRecordNo, medicalRecordNo));
            // 获取一级监护触发项
            FirstLevelVo firstLevelVoOfRed = CareLevelUtil.getFirstLevelVo(patientBaseInfo, firstLevelVo);
            if (ObjectUtil.isNotNull(firstLevelVoOfRed)) {
                careLevelTriggerItemVo.setFirstLevelVo(firstLevelVoOfRed);
                return R.ok("查询成功", careLevelTriggerItemVo);
            }
            // 获取二级监护信息视图对象
            TwoLevelVo twoLevelVoOfRed = CareLevelUtil.getTwoLevelVo(patientBaseInfo, twoLevelVo);
            if (ObjectUtil.isNotNull(twoLevelVoOfRed)) {
                careLevelTriggerItemVo.setTwoLevelVo(twoLevelVoOfRed);
                return R.ok("查询成功", careLevelTriggerItemVo);
            }
            return R.ok("查询成功", careLevelTriggerItemVo);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("查询失败");
        }
    }
}
